import { Button, type ButtonProps } from 'antd';
import { useRouteLoaderData } from 'react-router-dom';

import type { IAuthLoader } from '@/router/AuthLoader';
import { initUserInfo } from '@/store/modules/userStore';

interface IProps extends ButtonProps {
    auth?: string;
}

const SUPER_ADMIN_ROLE_ID = import.meta.env.VITE_APP_SUPER_ADMIN_ROLE_ID;

const AuthButton = ({ auth, children, ...rest }: IProps) => {
    const loaderData = useRouteLoaderData('layout') as IAuthLoader | undefined;
    const buttonList = loaderData?.buttonList ?? [];
    const userInfo = loaderData?.userInfo ?? initUserInfo;

    // 无 auth 属性时，不显示按钮
    if (!auth) return null;

    // 有权限 或者 超级管理员
    if (buttonList.includes(auth) || userInfo?.roleList?.includes(SUPER_ADMIN_ROLE_ID)) {
        return <Button {...rest}>{children}</Button>;
    }

    // 权限不足或者无权限 不显示按钮
    return null;
};

export default AuthButton;
